package cn.springcloud.fix.uaa.web.handler;

import cn.springcloud.fix.common.core.base.Result;
import cn.springcloud.fix.common.core.utils.WebUtil;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
        String msg;
        if (exception instanceof BadCredentialsException) {
            msg = "密码错误";
        } else {
            msg = exception.getMessage();
        }
        WebUtil.writeToResponse(response, Result.ERROR(401, msg));
    }
}
